use enigo::{
    Button,
    Coordinate::{Abs, Rel},
    Direction::Click,
    Enigo, Mouse, Settings,
};
use std::fs::File;
use std::io::{self, Read, Write};
use std::thread;
use std::time::Duration;

fn main() -> io::Result<()> {
    // 按1记录按键位置, 按2执行任务
    println!("按1记录鼠标位置, 按2执行解题任务");
    let mut input = String::new();
    io::stdin().read_line(&mut input).unwrap();
    let input = input.trim();
    if input == "1" {
        record_mouse_position()?;
    } else if input == "2" {
        // 执行解题任务
        println!("执行解题任务");
        execute_task()?;
    } else {
        println!("输入错误, 请重新输入");
    }

    Ok(())
}

// 输入数字, 转换为二进制数
fn input_to_binary(input: &str) -> u32 {
    let mut binary = 0;
    for digit in input.chars() {
        binary = binary << 1;
        if digit == '1' {
            binary |= 1;
        }
    }
    binary
}

fn execute_task() -> io::Result<()> {
    // 读取position.txt文件, 解析鼠标位置, 点击鼠标
    let mut file = File::open("position.txt")?;
    let mut positions = String::new();
    file.read_to_string(&mut positions)?;
    let positions: Vec<&str> = positions.split('\n').collect();
    let mut enigo = Enigo::new(&Settings::default()).unwrap();
    for position in positions {
        let position: Vec<&str> = position.split(':').collect();
        let x = position[1].trim().parse::<i32>().unwrap();
        let y = position[2].trim().parse::<i32>().unwrap();
        enigo.move_mouse(x, y, Abs).unwrap();
        enigo.button(Button::Left, Click).unwrap();
        thread::sleep(Duration::from_millis(1000));
    }
    Ok(())
}

fn record_mouse_position() -> io::Result<()> {
    let wait_time = Duration::from_secs(1);
    let enigo = Enigo::new(&Settings::default()).unwrap();
    let mut file = File::create("position.txt")?;

    // 记录9个鼠标位置, 并把它们写入文件
    for i in 0..9 {
        println!("将鼠标移动到第{}位置(从高位到低位), 按回车键继续...", i + 1);
        pause();
        println!("1秒后开始记录第{}位置", i + 1);
        thread::sleep(wait_time);
        println!("mouse location: {:?}", enigo.location().unwrap());
        let (x, y) = enigo.location().unwrap();
        writeln!(&mut file, "Mouse position: ({}, {})", x, y)?;
    }

    Ok(())
}

fn pause() {
    let mut input = String::new();
    io::stdout().flush().unwrap(); // 确保提示信息立即显示
    io::stdin().read_line(&mut input).unwrap(); // 等待用户输入
}
